<template>
  <div class="main-container">
    <!-- 侧边栏 -->
    <div class="sidebar" v-if="note!==''">
      <div class="sidebar-title">浏览CAD图纸</div>
      <!-- Button to view the remark -->
      <button class="sidebar-button" @click="viewRemark">查看批注意见</button>
      <button class="sidebar-button" @click="startDrawingCircle">圆形批注</button>
      <button class="sidebar-button" @click="startDrawingText">文字批注</button>
      <button class="sidebar-button" @click="startDrawingArrow">箭头批注</button>
      <button class="sidebar-button" @click="startDrawingRectangle">矩形批注</button>
      <button class="sidebar-button" @click="deleteComment">🗑 删除批注</button>
      <button class="sidebar-button" @click="saveCommentToOriginalFolder">💾 提交批注</button>
      <div class="sidebar-divider"></div>
      <button class="sidebar-button">👥 demo1</button>
      <button class="sidebar-button">👥 demo2</button>
    </div>

    <!-- CAD 显示区域 -->
    <div class="canvas-container" id="mxdiv">
      <canvas id="myCanvas"></canvas>
    </div>
    <!-- Dialog for inputting "批注意见" -->
    <el-dialog
      title="请输入批注意见"
      :visible.sync="inputDialogVisible"
      width="30%"
      @close="handleInputDialogClose"
    >
      <el-input
        type="textarea"
        v-model="row.remark"
        placeholder="请输入批注意见"
        rows="4"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleInputDialogClose">取消</el-button>
        <el-button type="primary" @click="saveRemark">保存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提交批注"
      :visible.sync="remarkDialogVisible"
      width="30%"
    >
      <p>{{ row.remark || '暂无批注意见' }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submit">提交批注</el-button>
        <el-button @click="remarkDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import Mx from "mxdraw";
import {drawCircleAtTwoPoints} from './ts/drawCircle.js'
import {drawTextAtPoint} from './ts/drawText.js'
import {drawRectangleAtTwoPoints} from "./ts/drawRectangle.js"
import {drawArrow} from "./ts/drawArrow.js"
import {getUserProfile} from "@/api/system/user";
import {rejectProbeSignatureVerify, submitProbeSignatureToApproveReject} from "@/api/system/probeSignatureProcess";

export default {
  data() {
    return {
      projectId: null,
      msg: 'Hello World',
      id: null,
      logUserId: null,
      cadFile: '',
      isComment: false, // 是否加载批注数据
      inputDialogVisible: false,
      viewDialogVisible: false,
      remarkDialogVisible: false,
      note: '', // 驳回
      row: {
        remark: '',
        annotation: '',
      },// 数据
      jsonData:{
        "ver": 1,
        "view": {
          "ptView1": {
            "x": 2.2737367544323206e-13,
            "y": 575.3324347828386,
            "z": 0
          },
          "ptView2": {
            "x": 642.8604000002567,
            "y": -121.27883478265665,
            "z": 0
          }
        },
        "layers": [
          {
            "type": 4,
            "visible": true,
            "name": "0",
            "TypeName": "MxDbLayerTableRecord"
          },
          {
            "type": 4,
            "visible": true,
            "name": "Comment",
            "TypeName": "MxDbLayerTableRecord"
          }
        ],
        "groups": [],
        "entitys": [
          {
            "type": 4,
            "color": 16777215,
            "renderOrder": 30,
            "opacity": 1,
            "visible": true,
            "lineWidth": 0,
            "lineWidthByPixels": true,
            "dashArray": 0,
            "dashRatio": 0,
            "layer": "Comment",
            "guid": "CCBE5157-646A-45EB-9520-50F7A79A4448",
            "text": "踩踩踩踩踩",
            "position": {
              "datatype": 3,
              "value": [
                234.35379130444153,
                272.1775304348919,
                0
              ]
            },
            "height": 16,
            "padding": 0,
            "borderWidth": 0,
            "borderRadius": 0,
            "borderColor": "white",
            "fontFace": "Arial",
            "fontSize": 90,
            "fontWeight": "normal",
            "strokeWidth": 0,
            "strokeColor": "white",
            "angle": 0,
            "textAlign": "start",
            "textShadowBlur": 0,
            "textShadowOffsetX": 0,
            "textShadowOffsetY": 0,
            "scale": 1,
            "underline": false,
            "TypeName": "MxDbText",
            "group": []
          }
        ],
        "filename": "test.dwg",
        "savefile": "test_annotated.dwg"
      }
    };
  },
  created() {
    console.log("HelloWorld created");
    console.log('routeQuery:',this.$route.query);
    this.isComment = this.$route.query.isComment==='true';
    if(this.$route.query.projectId) {
      this.projectId = this.$route.query.projectId;
    }
    console.log("isComment", this.isComment);
    if(this.isComment) {
      this.row = this.$route.query.row;
    }
    if(this.$route.query.note==="submitToVerifyReject" || this.$route.query.note==="submitToApproveReject") {
      this.note = this.$route.query.note;
      this.row = this.$route.query.row;
    }
    if(this.note !== '') {
      this.inputDialogVisible = true;
    }
    getUserProfile().then(response => {
      this.logUserId = response.data.userId;
    });
    // this.getDraw();
  },
  mounted() {
    const self = this;
    // 创建MxDraw对像,打开test.dwg图纸
    Mx.MxFun.createMxObject({
      canvasId: "myCanvas",
      //cadFile: "http://localhost:8080/demo/buf/test.dwg.mxb1.wgh",  //后端程序转换dwg文件后的文件位置
      cadFile: '/demo/buf/test.dwg.mxb1.wgh',  //后端程序转换dwg文件后的文件位置
      //cadFile: "/demo/buf/ccc.dwg.mxb1.wgh",
      // cadFile: this.cadFile,
      callback(mxDrawObject, { canvas, canvasParent }) {
        canvasParent.className = "mxdiv";
        mxDrawObject.addEvent("loadComplete", () => {
          console.log("mx loadComplete");
          if(self.isComment) {
            console.log("加载批注数据");
            // 测试加载批注数据
            //mxDrawObject.loadMxEntityFromJson(self.jsonData);
            // 从数据源加载批注
            console.log("从数据源加载批注this.row.annotation", self.row.annotation);
            mxDrawObject.loadMxEntityFromJson(JSON.parse(self.row.annotation));
          } else {
            console.log("不加载批注数据");
          }
        });
      },
    })
    console.log("HelloWorld mounted, drawCircleAtTwoPoints");
  },
  methods: {
    // 加载dwg图纸信息
    async getDraw() {
      // 根据id获取信息
      // getDrawById(this.id).then(res => {
      //   const { code, msg, data } = res.data;
      //   if (code === 0) {
      //     this.cadFile = data.cadFile;
      //     console.log("this.cadFile", this.cadFile);
      //     this.jsonData = data.jsonData;
      //     console.log("this.jsonData", this.jsonData);
      //   } else {
      //     this.$message.error("获取图纸信息失败: " + msg);
      //   }
      // }).catch(err => {
      //   console.error(err);
      //   this.$message.error("获取图纸信息失败：服务器未响应");
      // });
    },
    startDrawingCircle() {
      // 这里可以调用画圆的函数
      console.log("开始画圆");
      drawCircleAtTwoPoints();
    },
    startDrawingText() {
      // 这里可以调用画文字的函数
      console.log("开始画文字");
      drawTextAtPoint();
    },
    startDrawingRectangle() {
      // 这里可以调用画矩形的函数
      console.log("开始画矩形");
      drawRectangleAtTwoPoints();
    },
    startDrawingArrow() {
      // 这里可以调用画箭头的函数
      console.log("开始画箭头");
      drawArrow();
    },
    handleInputDialogClose() {
      this.inputDialogVisible = false; // Close the input dialog
    },
    saveRemark() {
      if (!this.row.remark.trim()) {
        this.$message.error("批注意见不能为空！");
        return;
      }
      this.$message.success("批注意见已保存！");
      this.inputDialogVisible = false;
    },
    viewRemark() {
      this.inputDialogVisible = true; // Open the view dialog
    },
    saveCommentToOriginalFolder() {
      if (!this.row.remark.trim()) {
        this.$message.error("批注意见不能为空！");
        return;
      }
      this.remarkDialogVisible = true; // Open the remark dialog
    },
    submit() {
        const mxDrawObj = Mx.MxFun.getCurrentDraw();
        mxDrawObj.setPointMultipleSelect(true);  // 启用多点选择
        const savaData = mxDrawObj.saveMxEntityToObject(true);
        this.row.annotation = JSON.stringify(savaData);
        this.row.operatorId = this.logUserId;
        console.log('submit',this.row);
        console.log('annotation',this.row.annotation);
        if(this.note === 'submitToVerifyReject') {
          rejectProbeSignatureVerify(this.row).then(res => {
            const { code, msg } = res.data ? res.data : res;
            if (code === 200) {
              this.$message.success("批注已保存！");
              this.remarkDialogVisible = false;
            } else {
              this.$message.error("批注保存失败: " + msg);
            }
          }).catch(err => {
            console.error(err);
            this.$message.error("批注保存失败：服务器未响应");
          });
        } else if(this.note === 'submitToApproveReject') {
          submitProbeSignatureToApproveReject(this.row).then(res => {
            const { code, msg } = res.data ? res.data : res;
            if (code === 200) {
              this.$message.success("批注已保存！");
              this.remarkDialogVisible = false;
            } else {
              this.$message.error("批注保存失败: " + msg);
            }
          }).catch(err => {
            console.error(err);
            this.$message.error("批注保存失败：服务器未响应");
          });
        } else {
          console.log("没有驳回,参数不对");
        }
      // 操作成功后等待一秒返回上一级页面
      setTimeout(() => {
        // 关闭当前tabs
        this.$store.dispatch("tagsView/delView", this.$route);
        // 跳转路由
        this.$router.replace({
          name: "ProbeProjectDetail",
          query: {
            id: this.projectId
          }
        });
      }, 1000);
    },
    deleteComment() {
      const draw = Mx.MxFun.getCurrentDraw();
      const getPoint = new Mx.MrxDbgUiPrPoint(); // 获取点击点
      console.log('getAllMxEntity',draw.getAllMxEntity())
      // 提示用户点击批注对象
      draw.prompt?.("点击批注对象以删除");
      console.log("开始删除批注");

      // 使用 goWhile 持续监听点击
      getPoint.goWhile(() => {
        console.log("获取点击点");
        const pt = getPoint.value();
        console.log("pt", pt);

        // 将 pt 转换为 THREE.Vector2，使用屏幕坐标
        const screenPt = new THREE.Vector3(
          234.35379130444153,
          272.1775304348919,
          0
        );
        console.log("screenPt", screenPt);

        // 获取点击位置附近的所有对象
        const intersections = draw.getIntersectObjects(screenPt);
        console.log("intersections", intersections);

        if (intersections.length > 0) {
          const obj = intersections[0].object; // 获取第一个交点的对象

          // 判断图层是否是“Comment”
          if (obj.layer && obj.layer.toLowerCase() === "comment") {
            const typeName = obj.TypeName || obj.typeName || "未知类型";

            const confirmDelete = confirm(`你选择了一个 ${typeName} 批注，是否要删除？`);
            if (confirmDelete) {
              draw.removeObject(obj, true); // 删除对象
              alert("✅ 删除成功");
            } else {
              alert("❎ 已取消删除");
            }
          } else {
            alert("⚠️ 选中的不是批注对象");
          }

          getPoint.cancel(); // 停止拾取
        }
      });
    }
  },
};
</script>

<style scoped>
.main-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
  margin-left: 0 !important; /* 关键：覆盖父容器的 margin-left */
}

.sidebar {
  width: 180px;
  background-color: #2c2f36;
  color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.sidebar-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #00d1b2;
}

.sidebar-button {
  background-color: #3c3f46;
  color: #fff;
  border: none;
  padding: 10px;
  margin: 5px 0;
  text-align: left;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
  font-size: 14px;
}

.sidebar-button:hover {
  background-color: #50545c;
}

.sidebar-divider {
  border-top: 1px solid #555;
  margin: 10px 0;
}

.canvas-container {
  flex-grow: 1;
  background-color: black;
  position: relative;
}
/* .mxdiv极为重要，坚决别删除 */
.mxdiv {
  width: 100%;
  position: relative;
  height: 100vh;
}
canvas#myCanvas {
  width: 100%;
  height: 100%;
  display: block;
}

</style>
